package com.lhx.product.controller;

import com.alibaba.fastjson.JSONArray;
import com.lhx.product.domain.PmsProductAttrRelVo;

import java.util.*;
import java.util.stream.Collectors;

public class Text3 {


    public static void main(String[] args) {
        String str = "[\n" +
                "\t{\n" +
                "\t\t\"cid\": 1,\n" +
                "\t\t\"attrName\": \"黑色\"\n" +
                "\t}\n" +
                "\t{\n" +
                "\t\t\"cid\": 2,\n" +
                "\t\t\"attrName\": \"M\"\n" +
                "\t}\n" +
                "]\n" +
                "\n";


        List<PmsProductAttrRelVo> relVos = JSONArray.parseArray(str, PmsProductAttrRelVo.class);

        // 按cid分组
        Map<Integer, List<PmsProductAttrRelVo>> categoryById = relVos.stream()
                .collect(Collectors.groupingBy(PmsProductAttrRelVo::getId));

        // 获取所有唯一的cid
        Set<Integer> uniqueCids = new HashSet<>(categoryById.keySet());

        // 生成所有可能的组合
        List<Map<Integer, String>> combinations = generateCombinations(categoryById, uniqueCids);

        // 打印结果
        combinations.forEach(System.out::println);
    }

    private static List<Map<Integer, String>> generateCombinations(Map<Integer, List<PmsProductAttrRelVo>> categoryById, Set<Integer> uniqueCids) {
        List<Map<Integer, String>> result = new ArrayList<>();

        // 对每个唯一的cid，准备其attrName的列表
        List<List<String>> attrLists = uniqueCids.stream()
                .map(cid -> categoryById.getOrDefault(cid, Collections.emptyList()).stream()
                        .map(PmsProductAttrRelVo::getName)
                        .collect(Collectors.toList()))
                .collect(Collectors.toList());

        // 使用递归或迭代生成组合
        backtrack(attrLists, 0, new HashMap<>(), result);

        return result;
    }

    private static void backtrack(List<List<String>> attrLists, int index, Map<Integer, String> currentCombination, List<Map<Integer, String>> result) {
        if (index == attrLists.size()) {
            // 所有列表都已遍历，添加当前组合到结果中
            result.add(new HashMap<>(currentCombination));
        } else {
            List<String> currentList = attrLists.get(index);
            for (String attr : currentList) {
                // 添加当前attr到组合中，并处理下一个列表
                currentCombination.put(index + 1, attr); // 设置cid从1开始
                backtrack(attrLists, index + 1, currentCombination, result);
                // 回溯：移除当前attr，以便尝试下一个
                currentCombination.remove(index + 1);
            }
        }
    }



}
